package cn.kgc.edumsm.controller;

import cn.kgc.commonutils.R;
import cn.kgc.edumsm.service.MsmService;
import cn.kgc.edumsm.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName MsmController
 * @Description: TODO
 * @Author :郭建宾
 * @Date 2020/7/14
 * @Version V1.0
 **/
@Api(tags = "短信验证")
@RestController
//@CrossOrigin
@RequestMapping("/edumsm/msm")
public class MsmController {
    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    
    //发送短信的方法
    @ApiOperation(value = "发送短信")
    @GetMapping("send/{phone}")
    public R sendMsm(@PathVariable String phone){
        //1 从redis 获取验证码，如果获取到直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)){
            return R.ok();
        }
        //如果redis获取不到，进行阿里云发送
        //生成随机值，传递阿里云进行发送
        code = RandomUtil.getFourBitRandom();
        Map<String,Object> param = new HashMap<>();
        param.put("code",code);
        //调用service 发送短信的方法
        boolean isSend= msmService.send(param,phone);
        if(isSend){
            //发送成功，把发送成功验证码放到redis里
            //设置有效时间
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.ok();
        }else {
            return R.error().message("短信验证失败");
        }
    }
}
